import Msg from './Message.js';
// import Util from '../Util.js';

let socket;

export default class Http {
    constructor(skt) {
        socket = skt;

        socket.emit('connection', JSON.parse(window.localStorage['user']));

        socket.on('system/app/save-status', (data) => {
            if (!data.status) {
                new Msg({ icon: '../../images//system/system.webp' }, `${data.type.toUpperCase()}配置信息上传失败！`);
            }
        });

        socket.on('welcome', (data) => {
            const content = data.text;

            // 收到欢迎事件表明是第一次登录发送请求创建ReadMe.md文件
            socket.emit('/application/Vititor/data/save/', {
                user: JSON.parse(window.localStorage['user']),
                fileName: 'README',
                text: '',
                docType: 'Markdown',
            });

            socket.removeListener('/application/Vititor/data/save/');
            socket.on('/application/Vititor/data/save/', (data) => {
                const app = JSON.parse(data);
                desktop.addApp(app);
                // 需要服务器传递一个完整app对象回来
                new Msg(app.app, content);
            });
        })
    }

    static ajax(op) {
        const options = {
            url: op.url,
            method: op.method || 'POST',
            success: op.success,
            error: op.error,
            data: op.data,
            contentType: op.contentType || 'application/json',
            timeout: op.timeout || 5000,
        }

        const xhr = new XMLHttpRequest();

        xhr.timeout = options.timeout;

        xhr.open(options.method, options.url, true);
        xhr.setRequestHeader("Content-type", options.contentType);

        xhr.send(options.data);

        xhr.onreadystatechange = (data) => {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    options.success && options.success(data.currentTarget);
                } else {
                    options.error && options.error(data);
                }
            }
        }
    }

    static upload(type, data) {
        if (type === 'app') {
            try {
                socket.emit('system/app/save', JSON.stringify({ user: window.localStorage['user'], app: data }));
            } catch {
                // 刷新时会重复上传，错误会阻止这一行为，所以就不修改或处理了
            }
        }
    }
}
